<!DOCTYPE html>
<html>
<head>
    <title>IPTV频道管理</title>
    {% include 'system/common/header.html' %}
</head>
<body class="pear-container">
    <!-- 搜索框 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">频道名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="channelName" placeholder="请输入频道名称" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">频道分类</label>
                        <div class="layui-input-inline">
                            <select name="category">
                                {% for category in categories %}
                                <option value="{{ category.name }}">{{ category.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="channel-query">
                            <i class="layui-icon layui-icon-search"></i>查询
                        </button>
                        <button type="reset" class="pear-btn pear-btn-md">
                            <i class="layui-icon layui-icon-refresh"></i>重置
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 数据表格 -->
    <div class="layui-card">
        <div class="layui-card-body">
            <table id="channel-table" lay-filter="channel-table"></table>
        </div>
    </div>

    <!-- 表格工具栏 -->
    <script type="text/html" id="channel-toolbar">
        
        {% if authorize("system:iptvadmin:add") %}
        <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="add">
            <i class="layui-icon layui-icon-add-1"></i>新增
        </button>
        {% endif %}
        {% if authorize("system:iptvadmin:iptvimport") %}
        <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="iptvimport">
          <i class="layui-icon layui-icon-add-1"></i>批量导入
        </button>
        {% endif %}
        {% if authorize("system:iptvadmin:remove") %}
        <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="batchRemove">
            <i class="layui-icon layui-icon-delete"></i>删除
        </button>
        {% endif %}
        <!-- 检查订阅 -->
        {% if authorize("system:iptvadmin:add") %}
        <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="rss-check" title="该功能还未完善，测试阶段，请谨慎使用">
            <i class="layui-icon layui-icon-check"></i>检查订阅
        </button>
        {% endif %}
        
    </script>

    <!-- 行工具栏 -->
    <script type="text/html" id="channel-bar">
        {% if authorize("system:iptvadmin:edit") %}
        <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit">
            <i class="layui-icon layui-icon-edit"></i>
        </button>
        {% endif %}
        {% if authorize("system:iptvadmin:remove") %}
        <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove">
            <i class="layui-icon layui-icon-delete"></i>
        </button>
        {% endif %}
    </script>


    {% include 'system/common/footer.html' %}
    <script>
        layui.use(['table', 'form', 'jquery'], function() {
            let table = layui.table;
            let form = layui.form;
            let $ = layui.jquery;

            let MODULE_PATH = "/iptvadmin/";
            let isAllPagesSelected = false;  // 是否全选所有页面
            let selectedData = new Set();    // 存储选中的数据ID
            let totalCount = 0;             // 存储总数据条数
            let cols = [
                [
                    {type: 'checkbox', title: '全选', layEvent: 'selectAll', LAY_CHECKED: false},
                    {field: 'id', title: 'ID', sort: true},
                    {field: 'name', title: '频道名称'},
                    {field: 'category', title: '频道分类'},
                    {
                    field: 'url', 
                    title: '播放地址', 
                    width: 200,
                        templet: function(d) {
                            var url = d.url;
                            // 如果url长度大于60，则显示前8个字符和后8个字符，中间用星号代替
                            if (url && url.length > 8) {
                                var start = url.substring(0, 8);
                                var end = url.substring(url.length - 8);
                                var stars = Array(8).fill('*').join('');
                                return start + stars + end;
                            }
                            return url;
                        }
                    },
                    {field: 'create_time', title: '创建时间'},
                    {title: '操作', toolbar: '#channel-bar', align: 'center', width: 130}
                ]
            ];

            table.render({
                elem: '#channel-table',
                url: MODULE_PATH + 'query',
                page: true,
                cols: cols,
                skin: 'line',
                toolbar: '#channel-toolbar',
                defaultToolbar: [{
                    layEvent: 'refresh',
                    title: '刷新',
                    icon: 'layui-icon-refresh',
                }, 'filter', 'print', 'exports'],
                parseData: function(res) {
                    // 保存总数据条数
                    totalCount = res.count;
                    return res;
                },
                done: function(res) {
                    // 如果是全选状态，则选中当前页所有数据
                    if (isAllPagesSelected) {
                        this.elem.find('.layui-table-header th[data-type="checkbox"] input').prop('checked', true);
                        this.elem.find('.layui-table-body tr input[type="checkbox"]').each(function() {
                            $(this).prop('checked', true);
                            $(this).next().addClass('layui-form-checked');
                        });
                    }
                }
            });
            // 监听表头复选框点击事件
            table.on('checkbox(channel-table)', function(obj) {
                if (obj.type === 'all') {
                    if (obj.checked) {
                        // 点击全选时
                        layer.confirm(`是否选中所有页面的数据？(共${totalCount}条)`, {
                            btn: ['是','否'],
                            title: '提示'
                        }, function(index){
                            isAllPagesSelected = true;
                            layer.msg(`已选中全部 ${totalCount} 条数据`);
                            layer.close(index);
                        }, function(index){
                            // 仅选中当前页
                            isAllPagesSelected = false;
                            // 获取当前页数据
                            let currentPageData = table.cache['channel-table'];
                            currentPageData.forEach(item => {
                                if (item.id) selectedData.add(item.id);
                            });
                            layer.close(index);
                        });
                    } else {
                        // 取消全选
                        isAllPagesSelected = false;
                        selectedData.clear();
                    }
                } else if (obj.type === 'one') {
                    // 单个复选框选中/取消
                    if (obj.checked) {
                        selectedData.add(obj.data.id);
                    } else {
                        selectedData.delete(obj.data.id);
                        // 如果之前是全选状态，现在取消某一个，则取消全选状态
                        if (isAllPagesSelected) {
                            isAllPagesSelected = false;
                        }
                    }
                }
            });
            // 查询按钮点击事件
            form.on('submit(channel-query)', function(data) {
                table.reload('channel-table', {
                    where: data.field,
                    page: {curr: 1}
                });
                return false;
            });

            // 工具栏事件
            table.on('toolbar(channel-table)', function(obj) {
                if (obj.event === 'add') {
                    window.add();
                } else if (obj.event === 'iptvimport') {
                    window.iptvimport();
                } else if (obj.event === 'rss-check') {
                    checkSubscriptions();
                } else if (obj.event === 'refresh') {
                    window.refresh();
                } else if (obj.event === 'batchRemove') {
                    window.batchRemove(obj);
                } 
                
            });

            // 行工具栏事件
            table.on('tool(channel-table)', function(obj) {
                if (obj.event === 'remove') {
                    window.remove(obj);
                } else if (obj.event === 'edit') {
                    window.edit(obj);
                }
            });

            // 新增窗口
            window.add = function() {
                layer.open({
                    type: 2,
                    title: '新增频道',
                    shade: 0.1,
                    area: ['550px', '500px'],
                    content: MODULE_PATH + 'add'
                });
            }

            // 批量导入窗口
            window.iptvimport = function() {
                layer.open({
                    type: 2,
                    title: '批量导入',
                    shade: 0.1,
                    area: ['550px', '500px'],
                    content: MODULE_PATH + 'iptvimport'
                });
            }

            // 修改窗口
            window.edit = function(obj) {
                layer.open({
                    type: 2,
                    title: '修改频道',
                    shade: 0.1,
                    area: ['550px', '500px'],
                    content: MODULE_PATH + 'edit?id=' + obj.data['id']
                });
            }

            // 删除
            window.remove = function(obj) {
                layer.confirm('确定要删除该频道？', {
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    layer.close(index);
                    let loading = layer.load();
                    $.ajax({
                        url: MODULE_PATH + "remove",
                        data: {id: obj.data['id']},
                        dataType: 'json',
                        type: 'post',
                        success: function(result) {
                            layer.close(loading);
                            if (result.success) {
                                layer.msg(result.msg, {
                                    icon: 1,
                                    time: 1000
                                }, function() {
                                    obj.del();
                                });
                            } else {
                                layer.msg(result.msg, {
                                    icon: 2,
                                    time: 1000
                                });
                            }
                        }
                    })
                });
            }

            // 批量删除
            window.batchRemove = function(obj) {
                if (isAllPagesSelected) {
                    // 删除所有数据
                    layer.confirm(`确定要删除所有数据吗？(共${totalCount}条)`, {
                        icon: 3,
                        title: '警告',
                        btn: ['确定','取消']
                    }, function(index) {
                        layer.close(index);
                        let loading = layer.load();
                        $.ajax({
                            url: MODULE_PATH + "/batchRemove",
                            data: {all: true},
                            dataType: 'json',
                            type: 'post',
                            success: function(result) {
                                layer.close(loading);
                                if (result.success) {
                                    layer.msg(result.msg, {
                                        icon: 1,
                                        time: 1000
                                    }, function() {
                                        isAllPagesSelected = false;
                                        selectedData.clear();
                                        table.reload('channel-table');
                                    });
                                } else {
                                    layer.msg(result.msg, {
                                        icon: 2,
                                        time: 1000
                                    });
                                }
                            }
                        });
                    });
                } else {
                    // 删除选中数据
                    let ids = Array.from(selectedData);
                    if (ids.length === 0) {
                        layer.msg("未选中数据", {
                            icon: 2,
                            time: 1000
                        });
                        return false;
                    }
                    
                    layer.confirm(`确定要删除选中的 ${ids.length} 条数据吗？`, {
                        icon: 3,
                        title: '提示'
                    }, function(index) {
                        layer.close(index);
                        let loading = layer.load();
                        $.ajax({
                            url: MODULE_PATH + "/batchRemove",
                            data: {ids: ids},
                            dataType: 'json',
                            type: 'post',
                            success: function(result) {
                                layer.close(loading);
                                if (result.success) {
                                    layer.msg(result.msg, {
                                        icon: 1,
                                        time: 1000
                                    }, function() {
                                        selectedData.clear();
                                        table.reload('channel-table');
                                    });
                                } else {
                                    layer.msg(result.msg, {
                                        icon: 2,
                                        time: 1000
                                    });
                                }
                            }
                        });
                    });
                }
            }
            // 检查订阅函数
            function checkSubscriptions() {
                // 获取表格所有数据
                let tableData = table.cache['channel-table'];
                if (!tableData || tableData.length === 0) {
                    layer.msg('没有可检查的订阅', {icon: 2});
                    return;
                }

                // 显示进度条
                let loadIndex = layer.load(2, {shade: [0.3, '#fff']});
                let total = tableData.length;
                let checked = 0;
                let validCount = 0;
                let invalidCount = 0;

                // 添加自定义样式
                const styleId = 'channel-check-style';
                if (!document.getElementById(styleId)) {
                    const style = `
                        .channel-valid {
                            background-color: rgba(40, 167, 69, 0.2) !important;
                        }
                        .channel-valid td {
                            color: #28a745 !important;
                        }
                        .channel-invalid {
                            background-color: rgba(220, 53, 69, 0.2) !important;
                        }
                        .channel-invalid td {
                            color: #dc3545 !important;
                        }
                        .check-progress {
                            position: fixed;
                            top: 50%;
                            left: 50%;
                            transform: translate(-50%, -50%);
                            background: #fff;
                            padding: 20px;
                            border-radius: 4px;
                            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                            z-index: 19891015;
                        }
                        .check-progress-text {
                            text-align: center;
                            margin-bottom: 10px;
                        }
                        .check-progress-bar {
                            width: 300px;
                            height: 20px;
                            background: #f5f5f5;
                            border-radius: 10px;
                            overflow: hidden;
                        }
                        .check-progress-inner {
                            width: 0%;
                            height: 100%;
                            background: #009688;
                            transition: width 0.3s;
                        }
                    `;
                    $('<style>', {id: styleId}).text(style).appendTo('head');
                }

                // 创建进度显示
                const progressHtml = `
                    <div class="check-progress">
                        <div class="check-progress-text">正在检查订阅 (0/${total})</div>
                        <div class="check-progress-bar">
                            <div class="check-progress-inner"></div>
                        </div>
                    </div>
                `;
                const $progress = $(progressHtml).appendTo('body');

                // 检查单个订阅
                function checkSingleSubscription(item, index) {
                    if (!item.url) {
                        updateProgress();
                        return;
                    }
                    // console.log(item.url)
                    $.ajax({
                        url: '/iptvadmin/rss/check',
                        method: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({url: item.url}),
                        success: function(res) {
                            const tr = $(`#channel-table + .layui-table-view tr[data-index="${index}"]`);
                            if (res.success) {
                                tr.removeClass('channel-invalid').addClass('channel-valid');
                                validCount++;
                            } else {
                                tr.removeClass('channel-table-valid').addClass('channel-invalid');
                                invalidCount++;
                            }
                            updateProgress();
                        },
                        error: function() {
                            const tr = $(`#channel-table + .layui-table-view tr[data-index="${index}"]`);
                            tr.removeClass('channel-valid').addClass('channel-invalid');
                            invalidCount++;
                            updateProgress();
                        }
                    });
                }

                // 更新进度
                function updateProgress() {
                    checked++;
                    const percent = (checked / total * 100).toFixed(2) + '%';
                    $('.check-progress-text').text(`正在检查订阅 (${checked}/${total})`);
                    $('.check-progress-inner').css('width', percent);

                    // 检查是否全部完成
                    if (checked === total) {
                        setTimeout(() => {
                            layer.close(loadIndex);
                            $progress.remove();
                            layer.msg(`检查完成：${validCount}个有效，${invalidCount}个无效`, {
                                icon: 1,
                                time: 3000
                            });
                        }, 500);
                    }
                }

                // 批量处理，每次处理3个
                const batchSize = 3;
                for (let i = 0; i < tableData.length; i += batchSize) {
                    const batch = tableData.slice(i, i + batchSize);
                    batch.forEach((item, idx) => {
                        setTimeout(() => {
                            checkSingleSubscription(item, i + idx);
                        }, 100 * idx);
                    });
                }
            }
            
            // 刷新表格
            window.refresh = function() {
                table.reload('channel-table');
            }
        });
    
    </script>
</body>
</html>
